<template>
  <div>
    <p class="m-10 mb-20 placeholder">树形控件可拖拽</p>
    <el-tree
      draggable
      :data="menus"
      node-key="name"
      :props="props"
      @node-drop="reloadMenu"
    >
      <span slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span class="ml-30">
          <el-button @click.stop="showEdit(data)" type="text">
            编辑
          </el-button>
        </span>
      </span>
    </el-tree>
    <Dialog
      :dialogVisible.sync="dialogVisible"
      :menuInfo="menuInfo"
      @closeDialog="closeDialog"
      @sureDialog="sureDialog"
    />
  </div>
</template>

<script>
import menusArr from "@/router/menu";
import Dialog from "./components/Dialog";
export default {
  components: {
    Dialog
  },
  data() {
    return {
      dialogVisible: false,
      menuInfo: {},
      menus: JSON.parse(JSON.stringify(menusArr)),
      props: {
        label: "title",
        children: "children"
      }
    };
  },
  methods: {
    // 打开弹窗
    showEdit(data) {
      this.menuInfo = data;
      this.dialogVisible = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
    },
    // 提交表单
    sureDialog(formData) {
      this.changeMenu(this.menus, formData);
      // menus数组内有对象被替换，深拷贝一次避免无法触发响应式
      this.menus = JSON.parse(JSON.stringify(this.menus));
      this.closeDialog();
      this.reloadMenu();
    },
    // 刷新菜单
    reloadMenu() {
      this.$store.commit("common/RELOAD_MENU", this.menus);
    },
    // 递归修改menus
    changeMenu(menus, formData) {
      let keepOn = true;
      menus.forEach((item, index) => {
        if (item.name === formData.name) {
          menus[index] = formData;
          keepOn = false;
        }
        if (item.children && keepOn) {
          this.changeMenu(item.children, formData);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>
